package org.king.util;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class MailUtil {
    @Resource
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String username;

    public void sendMailMessage(Map<String, Object> data) {
        String email = (String) data.get("email");
        Integer code = (Integer) data.get("code");
        String type = (String) data.get("type");
        SimpleMailMessage message = switch (type){
            case "register" -> createMailMessage(email, "欢迎注册网站", "验证码:"+code+"有效时间3min");
            case "reset" -> createMailMessage(email, "重置密码", "验证码:"+code+"有效时间3min");
            default -> null;
        };
        if(message == null) return;
        mailSender.send(message);
    }

    private SimpleMailMessage createMailMessage(String email,String title,String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(title);
        message.setText(content);
        message.setTo(email);
        message.setFrom(username);
        return message;
    }
}
